package com.sfang.common.util.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sfang.common.base.collection.CustomKeyValuePair;
import com.sfang.common.base.collection.QuaternityTuple;

import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSetUtil {
    public static void templates(File fileRead,
                                 File fileSchemas,
                                 String fileWrite,
                                 String database,
                                 List<CustomKeyValuePair<String, Integer>> tables,
                                 boolean uat) {

        List<QuaternityTuple<String, String, String, String, String>> schemas
                = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader(fileSchemas));//构造一个BufferedReader类来读取文件
            String line = null;

            while ((line = br.readLine()) != null) {//使用readLine方法，一次读一行

                String[] values = line.split("\\t");
                if (tables.stream().anyMatch(t -> t.getKey().trim().equalsIgnoreCase(values[0].trim())))
                    schemas.add(QuaternityTuple.create(values[0], values[1], values[2], values.length > 3 ? values[3] : null, null));
            }

            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        List<CustomKeyValuePair<String, List<QuaternityTuple<String, String, String, String, String>>>> sorted
                = new ArrayList<>();

        schemas.stream()
                .collect(Collectors.groupingBy(QuaternityTuple::getFirst))
                .forEach((k, v) -> {
                    sorted.add(CustomKeyValuePair.create(k, v));
                });


        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileRead));//构造一个BufferedReader类来读取文件
            String line = null;

            while ((line = br.readLine()) != null) {//使用readLine方法，一次读一行
                sb.append(line);
            }

            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject template = JSON.parseObject(sb.toString());

        sorted.stream().sorted(Comparator.comparing(CustomKeyValuePair::getKey))
                .forEach(s -> {
                    String k = s.getKey();
                    Integer level = tables.stream().filter(t -> t.getKey().trim().equalsIgnoreCase(k)).findFirst().get().getValue();
                    List<QuaternityTuple<String, String, String, String, String>> v = s.getValue();

                    String title = (uat ? "uat_" : "prod_") + level+"_" + "mysql_kudu_" + k;
                    String description = (uat ? "uat_" : "prod_") + level+"_"  + "mysql_kudu_" + k;

                    ((JSONObject) template.get("pipelineConfig")).put("title", title);
                    ((JSONObject) template.get("pipelineConfig")).put("description", description);

                    template.getJSONObject("pipelineConfig").getJSONObject("info").put("title", title);
                    template.getJSONObject("pipelineConfig").getJSONObject("info").put("description", description);

                    template.getJSONObject("pipelineConfig")
                            .getJSONArray("stages")
                            .getJSONObject(0)
                            .getJSONArray("configuration").getJSONObject(1)
                            .put("value", String.format("SELECT * FROM %s WHERE %s>0 ORDER BY %s ASC",
                                    k,
                                    v.stream().filter(c -> c.getFourth() != null && c.getFourth().equalsIgnoreCase("pri")).findFirst().get().getSecond(),
                                    v.stream().filter(c -> c.getFourth() != null && c.getFourth().equalsIgnoreCase("pri")).findFirst().get().getSecond()
                            ));

                    template.getJSONObject("pipelineConfig")
                            .getJSONArray("stages")
                            .getJSONObject(0)
                            .getJSONArray("configuration").getJSONObject(3)
                            .put("value",
                                    v.stream().filter(c -> c.getFourth() != null && c.getFourth().equalsIgnoreCase("pri")).findFirst().get().getSecond()
                            );

                    template.getJSONObject("pipelineConfig")
                            .getJSONArray("stages")
                            .getJSONObject(1)
                            .getJSONArray("configuration").getJSONObject(5)
                            .put("value", String.format("impala::%s.%s",
                                    database,
                                    k
                            ));

                    BufferedWriter bw = null;
                    try {
                        bw = new BufferedWriter(new OutputStreamWriter(
                                new FileOutputStream(fileWrite + (uat ? "uat_" : "prod_") + level+"_"  + k + ".json"), "UTF-8"));
                        bw.write(template.toJSONString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (bw != null) {
                            try {
                                bw.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });

    }
}
